//
//  SPStateViewController.m
//  Sport
//
//  Created by Cass on 2018/1/25.
//  Copyright © 2018年 Cass. All rights reserved.
//

#import "SPStateViewController.h"
#import "SPStateCell.h"
#import "SPHomeStateModel.h"
#import "SPtime.h"
#import "ZPImageMagnification.h"
#import "SPReviewCell.h"
//#import "SPCommentModel.h"
#import "SPUser.h"
#import "SPComment.h"
#import "SPCommentFrame.h"
#import "SPToolBar.h"
#define MAXSCREEN [UIScreen mainScreen].bounds.size.width
#define MAXWidth [UIScreen mainScreen].bounds.size.width-250
#define MAXHeight 100
#define MarginLeftRight 12
@interface SPStateViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImg;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *locLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) UILabel *contentLabel;
@property (nonatomic, strong) NSMutableArray *imagesArray;
@property (nonatomic, strong) NSMutableArray *imageViewsArray;
@property (weak, nonatomic) IBOutlet UIView *headerView;
//@property (nonatomic, strong) NSMutableArray  <SPCommentModel *>*comments;
@property (nonatomic, strong) NSMutableArray *comments;
@property (nonatomic, strong) NSMutableArray *users;
@property (nonatomic, strong) NSMutableArray *commentsFrame;
@property (nonatomic, weak) SPToolBar *toolBar;
@property(nonatomic, strong) NSString *fromName;

@end
CGRect lastCellRect;
@implementation SPStateViewController

- (void)viewWillAppear:(BOOL)animated{
    //添加对键盘的监控
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyBoardWillShow:(NSNotification *)note{
    //获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    //获取键盘高度
    CGRect keyBoardBounds = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyBoardBounds.size.height;
    //获取键盘动画时间
    CGFloat animationTime = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //定义动作
    void (^animation)(void) = ^void(void){
        self.toolBar.transform = CGAffineTransformMakeTranslation(0, - keyBoardHeight);
    };
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    }else{
        animation();
    }
//    CGRect rect = lastCellRect;
    
    [self.tableView setContentOffset:CGPointMake(0, keyBoardHeight) animated:YES];
}
- (void)keyBoardWillHide:(NSNotification *)note{
    //获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    //获取键盘动画时间
    CGFloat animationTime = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //定义动作
    void (^animation)(void) = ^void(void){
        self.toolBar.transform = CGAffineTransformIdentity;
        self.toolBar.textField.placeholder = @"写评论...";
    };
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    }else{
        animation();
    }
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}
//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [self.view endEditing:YES];
//}
- (NSMutableArray *)users{
    if (!_users) {
        _users = [[NSMutableArray alloc]init];
        SPUser *user0 = [[SPUser alloc]init];
        user0.userID = @"59";
        user0.nickname = @"王子豪";
        [_users addObject:user0];
        
        SPUser *user1 = [[SPUser alloc]init];
        user1.userID = @"60";
        user1.nickname = @"王大锤";
        [_users addObject:user1];
        
        SPUser *user2 = [[SPUser alloc]init];
        user2.userID = @"61";
        user2.nickname = @"王尼玛";
        [_users addObject:user2];
        
        SPUser *user3 = [[SPUser alloc]init];
        user3.userID = @"62";
        user3.nickname = @"王蚂蚁";
        [_users addObject:user3];
        
        SPUser *user4 = [[SPUser alloc]init];
        user4.userID = @"63";
        user4.nickname = @"王锤子";
        [_users addObject:user4];
        
        SPUser *user5 = [[SPUser alloc]init];
        user5.userID = @"64";
        user5.nickname = @"王锤锤";
        [_users addObject:user5];
    }
    return _users;
}

- (NSMutableArray *)comments{
    if (!_comments) {
        _comments = [[NSMutableArray alloc]init];
        
        SPComment *comment0 = [[SPComment alloc]init];
        comment0.fromUser = self.users[(NSInteger)(0 + (arc4random() % (2 - 0 + 1)))];
        comment0.text = @"我是猪";
        [_comments addObject:comment0];
        
        SPComment *comment1 = [[SPComment alloc]init];
        comment1.fromUser = self.users[[self randomNumber:0 to:3]];
        comment1.toUser = self.users[[self randomNumber:2 to:5]];
        comment1.text = @"你是猪";
        [_comments addObject:comment1];
        
        SPComment *comment2 = [[SPComment alloc]init];
        comment2.fromUser = self.users[[self randomNumber:0 to:3]];
        comment2.text = @"我不是猪";
        [_comments addObject:comment2];
        
        SPComment *comment3 = [[SPComment alloc]init];
        comment3.fromUser = self.users[[self randomNumber:0 to:3]];
        comment3.toUser = self.users[[self randomNumber:3 to:5]];
        comment3.text = @"你不是猪";
        [_comments addObject:comment3];
        
        SPComment *comment4 = [[SPComment alloc]init];
        comment4.fromUser = self.users[[self randomNumber:3 to:5]];
        comment4.text = @"你是哈批";
        [_comments addObject:comment4];
    }
    return _comments;
}
//- (void)tapBack{
//    [self.view endEditing:YES];
//}
- (void)viewDidLoad {
    [super viewDidLoad];
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBack)];
//    [self.view addGestureRecognizer:tap];
    [self headerSetBasic];
    [self setToolBar];
    self.tableView.delegate = self;
    self.tableView.separatorStyle = NO;
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 50, 0)];

    
    self.commentsFrame = [[NSMutableArray alloc]init];
    for (int i = 0; i < self.comments.count; i++) {
        SPCommentFrame *commentFrame = [[SPCommentFrame alloc]init];
        commentFrame.comment = self.comments[i];
//        commentFrame.maxW = MAXSCREEN;
        [self.commentsFrame addObject:commentFrame];
    }
    
    
}

- (void)_setupData{
    
}
- (NSMutableArray *)imagesArray{
    if (!_imagesArray) {
        _imagesArray = [NSMutableArray array];
    }
    return _imagesArray;
}
-(NSMutableArray *)imageViewsArray{
    if (!_imageViewsArray) {
        _imageViewsArray = [NSMutableArray array];
    }
    return _imageViewsArray;
}

- (void)setToolBar{
    SPToolBar *toolBar = [[[NSBundle mainBundle]loadNibNamed:@"SPToolBar" owner:nil options:nil] lastObject];
    [toolBar.sendBtn addTarget:self action:@selector(sendBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:toolBar];
    self.toolBar = toolBar;
    [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.right.mas_equalTo(self.view.mas_right);
        make.left.mas_equalTo(self.view.mas_left);
        make.height.mas_equalTo(50);
    }];
    
}
- (void)sendBtnClick{
    [self.view endEditing:YES];
}
- (void)headerSetBasic{
    if (self.stateModel.photo.length) {
        NSArray *images = [self.stateModel.photo componentsSeparatedByString:@"-"];
        for (NSString *url in images) {
            [self.imagesArray addObject:url];
        }
    }
    [self.iconImg sd_setImageWithURL:[NSURL URLWithString:self.stateModel.headimage] placeholderImage:[UIImage imageNamed:@"ha"]];
    self.iconImg.layer.cornerRadius = self.iconImg.bounds.size.width / 2;
    self.iconImg.layer.masksToBounds = YES;
    self.nameLabel.text = self.stateModel.nickname;
    self.timeLabel.text = [[SPtime sharedTime] timeWithCreatTime:self.stateModel.datetime];
    self.locLabel.text = self.stateModel.address;
    UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.iconImg.frame), CGRectGetMaxY(self.iconImg.frame) + 10, SCREEN_WIDTH - 2 * MarginLeftRight, 40)];
    contentLabel.text = self.stateModel.message;
    contentLabel.textColor = [UIColor blackColor];
    contentLabel.font = [UIFont systemFontOfSize:15];
    contentLabel.numberOfLines = 0;
    contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [contentLabel sizeToFit];
    [self.headerView addSubview:contentLabel];
    self.contentLabel = contentLabel;
    
    if (self.imagesArray.count == 1) {
        CGFloat imageViewWH = (SCREEN_WIDTH - 3 * MarginLeftRight) / 3;
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.contentLabel.frame), CGRectGetMaxY(self.contentLabel.frame) + 10, MAXWidth, MAXHeight)];
        imageview.backgroundColor = [UIColor whiteColor];
        [imageview sd_setImageWithURL:[NSURL URLWithString:self.imagesArray[0]] placeholderImage:[UIImage imageNamed:@"ha"]];
        //    [imageview.image scaleImageWithSize:CGSizeMake(MAXWidth, MAXHeight)];
        //    [imageview sizeToFit];
        UITapGestureRecognizer *tag1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bigImage:)];
        [imageview addGestureRecognizer:tag1];
        imageview.userInteractionEnabled = YES;
        [self.headerView addSubview:imageview];
        [self.imageViewsArray addObject:imageview];
        self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(imageview.frame) + 10, SCREEN_WIDTH, 44);
    }else if (self.imagesArray.count == 2){
        CGFloat imageViewWH = (SCREEN_WIDTH - 3 * MarginLeftRight) / 3;
        for (NSInteger i = 0; i < self.imagesArray.count; i++) {
            UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(MarginLeftRight + (i % 2) * (imageViewWH + MarginLeftRight), CGRectGetMaxY(contentLabel.frame) + 10, imageViewWH, imageViewWH)];
            imageview.backgroundColor = [UIColor whiteColor];
            [imageview sd_setImageWithURL:[NSURL URLWithString:self.imagesArray[i]] placeholderImage:[UIImage imageNamed:@"ha"]];
            UITapGestureRecognizer *tag1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bigImage:)];
            [imageview addGestureRecognizer:tag1];
            imageview.userInteractionEnabled = YES;
            [self.headerView addSubview:imageview];
            [self.imageViewsArray addObject:imageview];
            self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(imageview.frame) + 10, SCREEN_WIDTH, 44);
        }
    }else{
        CGFloat imageViewWH = (SCREEN_WIDTH - 4 * MarginLeftRight) / 3;
        for (NSInteger i = 0; i < self.imagesArray.count; i++) {
            UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(MarginLeftRight + (i % 3) * (imageViewWH + MarginLeftRight), CGRectGetMaxY(contentLabel.frame) + 10 + (i / 3) * (imageViewWH + MarginLeftRight), imageViewWH, imageViewWH)];
            imageview.backgroundColor = [UIColor whiteColor];
            [imageview sd_setImageWithURL:[NSURL URLWithString:self.imagesArray[i]] placeholderImage:[UIImage imageNamed:@"ha"]];
            UITapGestureRecognizer *tag1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bigImage:)];
            [imageview addGestureRecognizer:tag1];
            imageview.userInteractionEnabled = YES;
            [self.headerView addSubview:imageview];
            [self.imageViewsArray addObject:imageview];
            self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(imageview.frame), SCREEN_WIDTH, 44);
        }
    }
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetMaxY(self.bottomView.frame));
}
- (void)bigImage:(UITapGestureRecognizer *)gesture{
    [ZPImageMagnification scanBigImageWithImageView:(UIImageView *)gesture.self.view alpha:1];
}
#pragma mark - UITableViewDataSource&UITableViewDelegate -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.comments.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SPReviewCell *cell = [SPReviewCell cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SPCommentFrame *commentFrame = self.commentsFrame[indexPath.row];
    cell.commentFrame = commentFrame;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CGRect rect = [tableView rectForRowAtIndexPath:indexPath];
    UITextField *textField = [[UITextField alloc]initWithFrame:rect];
    [self.tableView addSubview:textField];
    [textField becomeFirstResponder];
    SPCommentFrame *commentFrame = self.commentsFrame[indexPath.row];
    self.fromName =  commentFrame.comment.fromUser.nickname;
    
    self.toolBar.textField.placeholder = [NSString stringWithFormat:@"回复%@:",self.fromName];
}

- (NSInteger)randomNumber:(NSInteger)from to:(NSInteger)to
{
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
